package namespace.jcu.mobile.library.system;

import java.util.ArrayList;
import java.util.List;


import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseException;

 
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;
 
public class SearchBookActivity extends Activity implements SearchView.OnQueryTextListener,
SearchView.OnCloseListener {
 
	
	ArrayList<BookRecord> bookList;
	ArrayList<BookRecord> searchBookList;
    private ListView mListView;
    private SearchView searchView;
    private List<ParseObject> result;
    private bookListAdapter mAdapter;
    private BookRecord bookUpdater;
    private TabHost mTabHost;
    Dialog dialog;

    
	private void setupTabHost() {
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchbook_layout);
        
        Parse.initialize(this, "1GlGZQ1XWU34mHgFyDHZiZRr6HTTSWOZo2nSAowy", "GKVclKTd6TIPxLVPPbDiyvzAMoWA2XLf4ZdZYFwI");
 
        searchView = (SearchView) findViewById(R.id.search);
        searchView.setIconifiedByDefault(false);
        searchView.setOnQueryTextListener(this);
        searchView.setOnCloseListener(this);
        bookList = new ArrayList<BookRecord>();
        searchBookList = new ArrayList<BookRecord>();
        dialog = ProgressDialog.show(SearchBookActivity.this, "", "Loading...");
        ParseQuery pquery = new ParseQuery("Book");
        pquery.findInBackground(new FindCallback() {
            public void done(final List<ParseObject> queryResult, ParseException e) {
            if (e == null) {
            	new Thread() {
                	
                    public void run() {
                
                        try{
                  	      result = queryResult;

                    } catch (Exception e) {

                    Log.e("tag", e.getMessage());

                    }

                    // dismiss the progress dialog
                    dialog.dismiss();

                    }

                    }.start();

    	      
    	    } else {
    	      // something went wrong
    	    }
         }
        });
        

       

		setupTabHost();
		mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
		
        mListView = (ListView) findViewById(R.id.list);

		
		setupTab(new TextView(this), "Title");
		setupTab(new TextView(this), "Author");
		setupTab(new TextView(this), "Year");
		setupTab(new TextView(this), "ISBN");

		
		mTabHost.setCurrentTabByTag("ISBN");
		mTabHost.setCurrentTabByTag("Title");  

    }
    
  
    
    protected Dialog onCreateDialog() {
    		dialog = ProgressDialog.show(this, "Please Wait", "Data are retreiving from Database ... ", true);
    		return dialog;
    	}
    
    
    
    
    private void setupTab(final View view, final String tag) {
		View tabview = createTabView(mTabHost.getContext(), tag);

		TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(mListView.getId());


		mTabHost.addTab(setContent);

	}
    
	private static View createTabView(final Context context, final String text) {
		View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
		TextView tv = (TextView) view.findViewById(R.id.tabsText);
		tv.setText(text);
		return view;
	}
      
    public boolean onQueryTextChange(String newText) {
        showResults(newText);
        return false;
    }
 
    public boolean onQueryTextSubmit(String query) {
        showResults(query);
        return false;
    }
 
    public boolean onClose() {
        showResults("");
        return false;
    }
    private void showResults(String query) {
    	
    	String status;
    	
    	searchBookList.clear();
    	if (mTabHost.getCurrentTabTag() == "Author")
    	{
	      for(int i=0; i<result.size(); i++)
          {
	    	  if (result.get(i).getString("Author").contains(query))
	    	  {
	    		if (result.get(i).getBoolean("Available_Status") == true)
	    		{
	    			status = "Currently Available";
	    		}
	    		else 
	    		{
	    			status = "On Loan";
	    		}
	    		
	    	  	bookUpdater = new BookRecord(result.get(i).getString("Title"), result.get(i).getString("Author"), status, 
	    	  	"ISBN : " +result.get(i).getString("ISBN"), ((ParseFile) result.get(i).get("Image")).getUrl().toString());
          		searchBookList.add(bookUpdater);
	    	  }
          }
    	}
    	else if (mTabHost.getCurrentTabTag() == "Title")
    	{
  	      for(int i=0; i<result.size(); i++)
          {
	    	  if (result.get(i).getString("Title").contains(query))
	    	  {
		    		if (result.get(i).getBoolean("Available_Status") == true)
		    		{
		    			status = "Currently Available";
		    		}
		    		else 
		    		{
		    			status = "On Loan";
		    		}
	    		  bookUpdater = new BookRecord(result.get(i).getString("Title"), result.get(i).getString("Author"), status, 
	    			"ISBN : " +result.get(i).getString("ISBN"), ((ParseFile) result.get(i).get("Image")).getUrl().toString());          		
	    		  searchBookList.add(bookUpdater);
	    	  }
          }
    	}
    	else if (mTabHost.getCurrentTabTag() == "Year")
    	{
  	      for(int i=0; i<result.size(); i++)
          {
	    	  if (String.valueOf(result.get(i).getInt("Publish_Year")).contains(query))
	    	  {
		    		if (result.get(i).getBoolean("Available_Status") == true)
		    		{
		    			status = "Currently Available";
		    		}
		    		else 
		    		{
		    			status = "On Loan";
		    		}
	    		  bookUpdater = new BookRecord(result.get(i).getString("Title"), result.get(i).getString("Author"), status, 
	    			"ISBN : " +result.get(i).getString("ISBN"), ((ParseFile) result.get(i).get("Image")).getUrl().toString());          		
	    		  searchBookList.add(bookUpdater);
	    	  }
          }
    	}
    	else 
    	{
  	      for(int i=0; i<result.size(); i++)
          {
	    	  if (result.get(i).getString("ISBN").contains(query))
	    	  {
		    		if (result.get(i).getBoolean("Available_Status") == true)
		    		{
		    			status = "Currently Available";
		    		}
		    		else 
		    		{
		    			status = "On Loan";
		    		}
	    		  bookUpdater = new BookRecord(result.get(i).getString("Title"), result.get(i).getString("Author"), status, 
	    			"ISBN : " +result.get(i).getString("ISBN"), ((ParseFile) result.get(i).get("Image")).getUrl().toString());          		
	    		  searchBookList.add(bookUpdater);
	    	  }
          }
		}
	      mListView.setAdapter(mAdapter);
	      mAdapter = new bookListAdapter(this, android.R.layout.simple_list_item_1, searchBookList);

    	



                    
            
     }
        
    
	public class bookListAdapter extends ArrayAdapter<BookRecord> {
		private ArrayList<BookRecord> bookList;

		public bookListAdapter(Context context, int textViewResourceId, ArrayList<BookRecord> bookList) {
			super(context, textViewResourceId, bookList);
			this.bookList = bookList;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.searchbook_result, null);
			}
			
			BookRecord bookrecord = bookList.get(position);
			if (bookrecord != null) {
				TextView title = (TextView) v.findViewById(R.id.title);
				TextView author = (TextView) v.findViewById(R.id.author);
				TextView availableStatus = (TextView) v.findViewById(R.id.availableStatus);
				TextView isbn = (TextView) v.findViewById(R.id.isbn);
				
				LoaderImageView image = (LoaderImageView) v.findViewById(R.id.loaderImageView);
				image.setImageDrawable(bookrecord.imageURL);


				if (title != null) {
					title.setText(bookrecord.title);
				}

				if(author != null) {
					author.setText(bookrecord.author );
				}
				
				if (availableStatus != null) {
					availableStatus.setText(bookrecord.availableStatus);
				}
				
				if (isbn != null) {
					isbn.setText(bookrecord.isbn);
				}
				
				
			}
			return v;
		}
	}
	
	public class BookRecord {
		public String title;
		public String author;
		public String availableStatus;
		public String isbn;
		public String imageURL;
		
		public BookRecord(String title, String author, String availableStatus, String isbn, String imageURL) {
			this.title = title;
			this.author = author;
			this.availableStatus = availableStatus;
			this.isbn = isbn;
			this.imageURL = imageURL;
		}
	}
}